<!--
  * 仓库主仓/移动仓
  *
-->
<template>
  <a-card class="tree-container" :style="{ height: appConfigStore.getLayoutContentClientRect.height + 'px' }" :bodyStyle="{ height: 'calc(100% - 56px)', overflowY: 'auto' }">
    <template #title>
      <div style="display: flex; align-items: center; justify-content: space-between; width: 100%">
        <span style="font-size: 14px">仓库列表</span>
        <!-- <a-button type="primary" size="small" @click="showFormModal()">
          <span style="font-size: 12px" v-privilege="'warehouse:add'">新增</span>
        </a-button> -->
      </div>
    </template>
    <a-tree v-if="warehouseTreeData.length > 0" :selectedKeys="selectedKeys" :treeData="warehouseTreeData" v-model:expandedKeys="expandedKeys" :fieldNames="{ title: 'name', key: 'key' }" @select="onSelect">
      <template #title="{ name, id, data }">
        <template v-if="[-1, -2].includes(id)">
          <div class="line-item">
            <Icon icon="svg-icon:warehouse" />
            <span>{{ id === -1 ? '固定主仓' : id === -2 ? '司机-移动车仓' : '业务员-移动车仓' }}</span>
          </div>
        </template>
        <template v-else-if="!data?.warehouse_type">
          <div class="line-item">
            <Icon icon="svg-icon:warehouse-area" />
            <span>{{ name }}</span>
          </div>
        </template>
        <template v-else>
          <a-popover placement="right" trigger="hover">
            <template #content>
              <div class="popover-item-wrapper">
                <a-button size="small" type="link" @click="showFormModal(data)" v-privilege="'warehouse:edit'">编辑</a-button>
                <a-button size="small" danger type="link" @click="onDelete(id, name)" v-privilege="'warehouse:del'">删除</a-button>
              </div>
            </template>
            <div class="line-item">
              <Icon icon="svg-icon:warehouse-area" />
              <span class="item-name">{{ name }}</span>
              <span v-if="data.warehouse_type === 1"> ({{ getDescByValue('WAREHOUSE_ATTRIBUTE_TYPE', data.attribute_type) }}) </span>
            </div>
          </a-popover>
        </template>
      </template>
    </a-tree>
  </a-card>
</template>
<script setup lang="ts">
import _ from 'lodash'
import { message, Modal } from 'ant-design-vue'
import { warehouseApi } from '@/api/business/storage/warehouse-api'
import { errorSentry } from '@/lib/error-sentry'
import { useLoadingStore } from '@/store/modules/loading-store'
import { useAppConfigStore } from '@/store/modules/app-store'
import { useEnums } from '@/hooks/plugins/useEnums'
import Icon from '@/components/framework/icon/index.vue'
import eventEmitter from '@/lib/event-emitter'
import customEventName from '@/views/business/storage/warehouse/warehouse/warehouse-event-name'
import { WAREHOUSE_TYPE } from '@/constants/business/storage/warehouse/warehouse-const'
import { treeToList } from '@/utils/tree-util'
const loadingStore = useLoadingStore()
const appConfigStore = useAppConfigStore()
const { getDescByValue } = useEnums()
// ----------------------- 分类树的展示 ---------------------
// 默认展开所有
// 分类树形数据
const warehouseTreeData = ref<any[]>([])
const expandedKeys = computed(() => {
  return treeToList(warehouseTreeData.value).map((item) => item.key)
})

// 查询分类列表并构建仓库树
const selectedKeys = ref<string[]>([])
const queryData = async () => {
  const res = await warehouseApi.queryList()
  const { driverMobileWarehouse, mobileWarehouse, warehouse } = res.data

  function handleMobileWarehouseData(item) {
    const row = _.cloneDeep(item[0])
    return {
      code: row.code,
      name: row.man_name,
      accountable_id: row.accountable_id,
      accountable_type: row.accountable_type,
      warehouse_type: row.warehouse_type,
      status: row.status,
      sort: row.sort,
      key: `A-${item.map(({ id }) => id).join(',')}-${row.warehouse_type}`,
      id: item.map(({ id }) => id).join(','),
      children: _(item)
        .map((item) => {
          const { warehouse_type, ...values } = item
          return { ...values, name: getDescByValue('WAREHOUSE_ATTRIBUTE_TYPE', item.attribute_type), key: `${item.id}-${warehouse_type}` }
        })
        .sortBy('attribute_type')
        .value()
    }
  }
  const mobileWarehouseList = _(mobileWarehouse)
    .filter((item) => item?.code)
    .groupBy('code')
    .mapValues(handleMobileWarehouseData)
    .values()
    .sortBy('sort')
    .value()

  const driverMobileWarehouseList = _(driverMobileWarehouse)
    .filter((item) => item?.code)
    .groupBy('code')
    .mapValues(handleMobileWarehouseData)
    .values()
    .sortBy('sort')
    .value()

  warehouseTreeData.value = [
    {
      id: -1,
      key: '-1-1',
      name: '固定主仓',
      warehouse_type: 1,
      disabled: true,
      children: _(warehouse)
        .map((item) => ({ ...item, key: `${item.id}-${item.warehouse_type}` }))
        .sortBy(warehouse, 'sort')
        .value()
    },
    {
      id: -2,
      key: '-2-2',
      name: '司机-移动主仓',
      warehouse_type: 2,
      disabled: true,
      children: driverMobileWarehouseList
    },
    {
      id: -3,
      key: '-3-3',
      name: '业务员-移动主仓',
      warehouse_type: 2,
      disabled: true,
      children: mobileWarehouseList
    }
  ]
  if (warehouse.length > 0) {
    const defaultWarehouse = `${warehouseTreeData.value[0]?.children[0]?.id}-${warehouseTreeData.value[0]?.children[0]?.warehouse_type}`
    selectedKeys.value = [defaultWarehouse]
    eventEmitter.emit('Custom:queryInventoryList', { id: warehouseTreeData.value[0]?.children[0]?.id })
    eventEmitter.emit(customEventName.QueryLocationList, {
      warehouse_id: warehouseTreeData.value[0]?.children[0]?.id,
      warehouse_name: warehouseTreeData.value[0]?.children[0]?.name,
      warehouse_code: warehouseTreeData.value[0]?.children[0]?.code
    })
  }
}
eventEmitter.on(customEventName.QueryWarehouseList, queryData)

onMounted(queryData)

// 选中tree
function onSelect(keys: string[], { node }) {
  selectedKeys.value = keys
  eventEmitter.emit(customEventName.QueryLocationList, {
    warehouse_id: node.id,
    warehouse_name: node.name,
    warehouse_code: node.code
  })
}

// ---------------------------- 新增/编辑 -----------------------
function showFormModal(data?: any) {
  eventEmitter.emit(customEventName.WarehouseFormModal, {
    title: data ? '编辑仓库' : '新增仓库',
    data
  })
}

// ---------------------------- 删除 ----------------------------
function onDelete(ids: string, name: string) {
  Modal.confirm({
    title: '提示',
    content: `确定要删除${name}吗?`,
    okText: '删除',
    okType: 'danger',
    onOk() {
      requestDelete(ids)
    },
    cancelText: '取消',
    onCancel() {}
  })
}

//请求删除
async function requestDelete(ids: string) {
  loadingStore.show()
  try {
    await warehouseApi.delete(ids)
    message.success('删除成功')
    await queryData()
  } catch (e) {
    message.error(e.msg)
    errorSentry.captureError(e)
  } finally {
    loadingStore.hide()
  }
}
</script>
<style scoped lang="less">
/* 隐藏所有小三角 */
:deep(.ant-tree .ant-tree-switcher) {
  display: none;
}
:deep(.ant-card-body) {
  padding-top: 10px;
}
.tree-container {
  overflow-y: auto;
}
.popover-item-wrapper {
  display: flex;
  flex-direction: column;
}
.line-item {
  display: flex;
  gap: 4px;
  align-items: center;
}
.item-name {
  flex: 1;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}
</style>
